import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Session from '@/core/session'
import Storage from '@/core/storage'
import * as functions from '@/core/functions.js'
import Menu from '@/config/menu'

// import NodeLogin from '@/pages/nodeLogin/NodeLogin'
// import Backend from '@/pages/backend/Backend.vue'

// 引入 backend 路由
import BackendRouter from '@/router/backend/index.js'

const NodeLogin = () => import('@/pages/nodeLogin/NodeLogin')
const Backend = () => import('@/pages/backend/Backend.vue')

// const originalPush = Router.prototype.push
// Router.prototype.push = function push (location) {
//   return originalPush.call(this, location).catch(err => err)
// }

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/node-login',
      name: 'NodeLogin',
      component: NodeLogin,
      meta: {
        isLogin: false
      }
    },
    {
      path: '/',
      redirect: '/backend',
      meta: {
        isLogin: false
      }
    },
    {
      path: '/backend',
      name: 'Backend',
      component: Backend,
      children: [...BackendRouter]
    }
  ]
})

/**
 * 这里去解决 router.beforeEach 经常遇到的一个问题，死循环问题
 * 该问题的产生是由于 next() 方法中带有了参数导致的，所以再执行带有参数的 next() 时需要一个识别的动作，即下一次循环的时候不在执行
 */
var routerBeforeEach = 0
function gnext (next, params) {
  if (params) {
    if (routerBeforeEach === 0) {
      routerBeforeEach = 1
      next(params)
    } else {
      routerBeforeEach = 0
      next()
    }
  } else {
    next()
  }
}

function myNext (next, path, quer) {
  let query
  if (quer) {
    query = Object.assign({}, quer, Session.routerQuery())
  } else {
    query = Object.assign({}, Session.routerQuery())
  }
  gnext(next, { path: path, query: query })
}

function routerNext (param, bool) {
  let { to, next } = param
  if (bool === true) {
    gnext(next)
  } else {
    let query = Object.assign({}, to.query, Session.routerQuery())
    gnext(next, { path: to.path, query: query })
  }
}

router.beforeEach((to, from, next) => {
  if (to.meta && to.meta.isLogin === false) {
    // 不需要验证登录
    next()
    return
  }
  /**
   * 以下均是要用户验证的部分
   */
  // 用户信息是否存在
  if (store.state.user && store.state.user.loginUserId && store.state.user.isLogin === true) {
    routerNext({ to, from, next })
    return
  }

  /**
   * 用户信息不存在的情况
   * 1. 判断当前url链接当中是否存在 TOKEN_PARAM_NAME 参数，
   *  1). 如果存在 TOKEN_PARAM_NAME 参数则通过请求服务器后台获取用户数据信息
   *  2). 如果不存在 TOKEN_PARAM_NAME 参数则说么没有登录，需要进入站点登录页面
   */
  let jsessionid = Session.jsessionid()
  if (!jsessionid) {
    functions.gotoLoginUrl()
  } else {
    /**
     * 通过当前页面的链接地址，获取到 Menu 中的菜单数据，将当前菜单加入到 menu_init 执行体重
     * 场景例如：当前页面 F5 刷新
     */
    let menuCallback = () => {
      // 通过 fullPath 找到对应的左侧菜单
      let fullPath = to.fullPath
      // let fullPathArray = fullPath.split('?')
      let fullPathArray
      if (fullPath.indexOf('&jsessionid') !== -1) {
        fullPathArray = fullPath.split('&jsessionid')
      } else {
        fullPathArray = fullPath.split('?')
      }
      if (fullPathArray && fullPathArray[0]) {
        fullPath = fullPathArray[0]
      }
      let itemmenu = null
      for (let i in Menu) {
        let men = Menu[i]
        if (men.path === fullPath) {
          itemmenu = men
          break
        } else if (men.children && men.children.length > 0) {
          let children = men.children
          for (let j in children) {
            let cPath = children[j].path
            if (fullPath.indexOf(cPath) === 0) {
              itemmenu = men
            }
          }
        }
      }
      if (itemmenu) {
        // 找到了
        store.commit('menu_init', {
          menu: itemmenu,
          fullPath: fullPath
        })
      }
      next()
    }
    Vue.prototype.$post('/site/info').then(
      response => {
        if (response && response.site) {
          store.commit('site_init', response)
        }
      },
      error => {
        console.error(error)
      }
    ).finally(() => {
      // 自动进入到设计页面后台
      let href = Storage.getOnceTempHref()
      if (href) {
        myNext(next, href)
        return
      }
      menuCallback()
    })
  }
})

export default router
